﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public class TrainingsTrainersCollection : AbstractCollection
    {
        /// <summary>
        /// Стaтическая коллекция 
        /// </summary>
        protected static List<TrainingsTrainers> _list;

        /// <summary>
        /// Список объектов
        /// </summary>
        public List<TrainingsTrainers> TrainingsTrainersList
        {
            get
            {
                return Entities.TrainingsTrainers.ToList();
                if (_list == null)
                    _list = DB.Entities.TrainingsTrainers.ToList();
                return _list;
            }
        }

        /// <summary>
        /// список активных объектов
        /// </summary>
        public List<TrainingsTrainers> TrainingsTrainersActiveList
        {
            get
            {
                var result = new List<TrainingsTrainers>();
                if (TrainingsTrainersList.Count < 1) return result;
                result.AddRange(TrainingsTrainersList.Where(item => item.IsActive));
                return result;
            }
        }

        #region Overrides of AbstractCollection

        /// <summary>
        /// Обновление элемента в коллекции
        /// </summary>
        /// <param name="item">Новый элемент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        /// <returns>Результат операции</returns>
        public bool Update(object item, string userLogin)
        {
            var newObject = (TrainingsTrainers) item;
            if (newObject == null)
                return false;

            var object4Update = GetItemByIdFromDatabase(newObject.GetKeyValue()) as TrainingsTrainers;
            if (object4Update == null)
                return false;

            if (!string.IsNullOrEmpty(newObject.Name))
                object4Update.Name = newObject.Name;

            if (!string.IsNullOrEmpty(newObject.Email))
                object4Update.Email = newObject.Email;

            if (!string.IsNullOrEmpty(newObject.Phone))
                object4Update.Phone = newObject.Phone;

            if (!string.IsNullOrEmpty(newObject.CommentsEn))
                object4Update.CommentsEn = newObject.CommentsEn;

            if (!string.IsNullOrEmpty(newObject.CommentsRu))
                object4Update.CommentsRu = newObject.CommentsRu;

            object4Update.IdTrainingsCenter = newObject.IdTrainingsCenter;

            object4Update.IsActive = newObject.IsActive;
            return base.Update(object4Update, userLogin);
        }

        /// <summary>
        /// Получение списка элементов
        /// </summary>
        /// <returns>Список элементов</returns>
        public override List<object> GetList()
        {
            return new List<object>(TrainingsTrainersList);
        }

        /// <summary>
        /// Получение типа текущего элемента
        /// </summary>
        /// <returns></returns>
        protected override Type GetItemType()
        {
            return typeof (TrainingsTrainers);
        }

        #endregion

        #region Extended properties

        /// <summary>
        /// Формируес список тренеров с первым именем "Выбрать всех"
        /// </summary>
        public List<TrainingsTrainers> DropDownList
        {
            get
            {
                var result = new List<TrainingsTrainers>();
                var selectAllItem = new TrainingsTrainers {Name = "Выбрать всех"};
                result.Add(selectAllItem);
                if (TrainingsTrainersActiveList.Count < 1) return result;
                result.AddRange(TrainingsTrainersActiveList.OrderBy(p => p.Name));
                return result;
            }
        }

        /// <summary>
        /// Возвращает тренеров в виде списка ресурсов для календаря
        /// </summary>
        /// <returns></returns>
        public List<SchedulerResources> TrainersAsSchedulerResources
        {
            get
            {
                var result = new List<SchedulerResources>();
                foreach (var trainer in TrainingsTrainersActiveList)
                {
                    var resourceItem = new SchedulerResources
                                           {
                                               ResourceID = trainer.IdTrainingsTrainer,
                                               UniqueID = trainer.IdTrainingsTrainer,
                                               ResourceName = trainer.Name
                                           };
                    //resourceItem.Color = trainer.IdTrainingsTrainer;
                    result.Add(resourceItem);
                }
                return result;
            }
        }

        #endregion

        #region Extended methods

        /// <summary>
        /// Формирует список тренеров из строки тренеров, разделенных сепаратором
        /// </summary>
        /// <param name="trainersStr"></param>
        /// <param name="separatorStr"></param>
        /// <returns></returns>
        public List<TrainingsTrainers> GetTrainersFromString(string trainersStr, char separatorStr = ';')
        {
            var result = new List<TrainingsTrainers>();
            string[] trainersArray = trainersStr.Split(separatorStr);
            foreach (string item in trainersArray)
            {
                int id = GetIdByName(item.Trim());
                if (id <= 0) continue;
                var trainerItem = (TrainingsTrainers) GetItemById(id);
                if (trainerItem != null)
                {
                    result.Add(trainerItem);
                }
            }
            return result;
        }

        /// <summary>
        /// Возвращает список тренеров, привязанных к курсу
        /// </summary>
        /// <param name="course"></param>
        /// <returns></returns>
        public List<TrainingsTrainers> GetTrainersListByCourse(TrainingsCourses course)
        {
            var result = new List<TrainingsTrainers>();
            var bindingCol = new TrainingsCoursesTrainersCollection();
            if (bindingCol.TrainingsCoursesTrainersList.Count < 1) return result;
            var trainersCol = new TrainingsTrainersCollection();
            foreach (TrainingsCoursesTrainers item in bindingCol.TrainingsCoursesTrainersList)
            {
                if (item.IdTrainingsCourse == course.IdTrainingsCourse)
                {
                    var trainer = (TrainingsTrainers) trainersCol.GetItemById(item.IdTrainingsTrainer);
                    if (trainer != null)
                        result.Add(trainer);
                }
            }
            return result;
        }

        /// <summary>
        /// Возвращает список тренеров, привязанных к курсу
        /// </summary>
        /// <param name="courseId"></param>
        /// <returns></returns>
        public List<TrainingsTrainers> GetTrainersListByCourseId(int courseId)
        {
            var coursesCol = new TrainingsCoursesCollection();
            var courseItem = (TrainingsCourses) coursesCol.GetItemById(courseId);
            return courseItem != null ? GetTrainersListByCourse(courseItem) : new List<TrainingsTrainers>();
        }

        #endregion

        /// <summary>
        /// Обнуление статической коллекции
        /// </summary>
        protected override void SetStaticListToNULL()
        {
            _list = null;
        }

        /// <summary>
        /// Получение статического списка для хранения объектов
        /// </summary>
        /// <returns></returns>
        public override object GetStaticCollection()
        {
            return _list;
        }

        /// <summary>
        /// Получение элемента из коллекции по идентификатору
        /// </summary>
        /// <param name="itemId">Идентификатор</param>
        /// <returns>Элемент</returns>
        public override object GetItemById(int itemId)
        {
            return Entities.TrainingsTrainers.Find(itemId);
        }
    }
}